import React, { useState, useMemo } from 'react';
import { useRemediation } from '@/contexts/RemediationContext';
import { type ComplianceItem } from '@/types/work';
import { type RemediationFormData } from '@/types/Remediation';
import ComplianceItemCard from './ComplianceItemCard';
import Pagination from './Pagination';
import './styles.css'; // 导入自定义样式
import {sortComplianceItems} from '@/utils/utils';

// 左侧面板组件
const LeftPanel: React.FC<{
  onCreateRemediation: (formData: RemediationFormData) => void;
}> = ({ onCreateRemediation }) => {
  const { pendingComplianceItems, remediationItems } = useRemediation();
  const [searchTerm, setSearchTerm] = useState('');
  
  // 分页状态
  const [currentPage, setCurrentPage] = useState(1);
  const itemsPerPage = 5; // 每页显示5个检查项
  
  // 检查项是否已用于创建整改项
  const isItemUsedInRemediation = (item: ComplianceItem) => {
    return remediationItems.some(remediation => remediation.item_id === item.id);
  };
  
  // 根据搜索词过滤检查项，并根据是否已用于创建整改项排序
  const filteredAndSortedItems = useMemo(() => {
    // 先过滤
    const filtered = pendingComplianceItems.filter(item => {
      if (!searchTerm) return true;
      
      const term = searchTerm.toLowerCase();
      return (
        item.title.toLowerCase().includes(term) ||
        (item.description && item.description.toLowerCase().includes(term))
      );
    });

    // 按照title进行排序
    let sorted = sortComplianceItems(filtered);
    
    // 再排序：未用于创建整改项的在前面
    sorted = sorted.sort((a, b) => {
      const aUsed = isItemUsedInRemediation(a);
      const bUsed = isItemUsedInRemediation(b);
      
      if (aUsed && !bUsed) return 1;
      if (!aUsed && bUsed) return -1;
      return 0;
    });
    return sorted;
  }, [pendingComplianceItems, searchTerm, remediationItems]);
  
  // 计算总页数
  const totalPages = Math.ceil(filteredAndSortedItems.length / itemsPerPage);
  
  // 获取当前页的检查项
  const currentItems = useMemo(() => {
    const startIndex = (currentPage - 1) * itemsPerPage;
    return filteredAndSortedItems.slice(startIndex, startIndex + itemsPerPage);
  }, [filteredAndSortedItems, currentPage, itemsPerPage]);
  
  // 处理页码变化
  const handlePageChange = (page: number) => {
    setCurrentPage(page);
  };

  return (
    <div className="h-full flex flex-col">
      <div className="p-4 border-b">
        <h2 className="text-lg font-semibold mb-4">待整改检查项</h2>
        
        <div className="relative mb-4">
          <input
            type="text"
            placeholder="搜索检查项..."
            value={searchTerm}
            onChange={(e) => setSearchTerm(e.target.value)}
            className="w-full p-2 pl-8 border rounded-md focus:outline-none focus:ring-2 focus:ring-primary/50"
          />
          <svg
            xmlns="http://www.w3.org/2000/svg"
            className="h-4 w-4 absolute left-2.5 top-3 text-muted-foreground"
            fill="none"
            viewBox="0 0 24 24"
            stroke="currentColor"
          >
            <path
              strokeLinecap="round"
              strokeLinejoin="round"
              strokeWidth={2}
              d="M21 21l-6-6m2-5a7 7 0 11-14 0 7 7 0 0114 0z"
            />
          </svg>
        </div>
        
        <div className="text-sm text-muted-foreground">
          共 <span className="font-medium">{filteredAndSortedItems.length}</span> 项
        </div>
      </div>
      
      {/* 使用自定义滚动条样式，自适应高度显示3-5个卡片 */}
      <div 
        className="overflow-y-auto p-4 custom-scrollbar" 
        style={{ 
          minHeight: "calc(3 * (7rem + 1rem))", // 最少显示三个卡片
          maxHeight: "calc(5 * (7rem + 1rem))", // 最多显示五个卡片
          height: "auto" // 自适应高度，但受到min和max的限制
        }}
      >
        {currentItems.length > 0 ? (
          currentItems.map(item => (
            <ComplianceItemCard
              key={item.id}
              item={item}
              onCreateRemediation={onCreateRemediation}
              isUsedInRemediation={isItemUsedInRemediation(item)}
            />
          ))
        ) : (
          <div className="text-center py-8 text-muted-foreground">
            {searchTerm ? '没有找到匹配的检查项' : '没有待整改的检查项'}
          </div>
        )}
      </div>
      
      {/* 分页控件 */}
      {filteredAndSortedItems.length > 0 && (
        <div className="border-t p-2">
          <Pagination
            currentPage={currentPage}
            totalPages={totalPages}
            onPageChange={handlePageChange}
          />
        </div>
      )}
    </div>
  );
};

export default LeftPanel;
